import React, { useEffect, useState ,useRef} from 'react';
import { Typography, Card, Button, message, Row, Col, Tabs } from 'antd';
import DataDashboard from '../../components/DataDashboard';
import TechCanvas from '../../components/TechCanvas';
import performanceMonitor from '../../utils/performance';
import './style.less';
import PerformanceVizCanvas from '../../utils/PerformanceVizCanvas'// 引入Canvas组件

const { Title, Paragraph } = Typography;
// 技术栈节点数据
const techNodes = [
  { id: 'react', name: 'React', category: 'frontend', size: 30, color: '#61dafb' },
  { id: 'typescript', name: 'TypeScript', category: 'frontend', size: 25, color: '#3178c6' },
  { id: 'vite', name: 'Vite', category: 'build', size: 20, color: '#646cff' },
  { id: 'router', name: 'React Router', category: 'frontend', size: 20, color: '#f44250' },
  { id: 'less', name: 'Less', category: 'styling', size: 18, color: '#1d365d' },
  { id: 'antd', name: 'Ant Design', category: 'ui', size: 25, color: '#eb2f96' },
  { id: 'axios', name: 'Axios', category: 'data', size: 18, color: '#5a29e4' },
  { id: 'echarts', name: 'ECharts', category: 'visualization', size: 22, color: '#aa314d' },
  { id: 'canvas', name: 'Canvas', category: 'visualization', size: 20, color: '#ff7e1e' },
  { id: 'frontend', name: '前端开发', category: 'direction', size: 35, color: '#ff4757' },
  { id: 'backend', name: '后端开发', category: 'direction', size: 35, color: '#2ed573' },
  { id: 'ai', name: '人工智能', category: 'direction', size: 35, color: '#5352ed' },
  { id: 'node', name: 'Node.js', category: 'backend', size: 22, color: '#68a063' },
  { id: 'python', name: 'Python', category: 'backend', size: 22, color: '#3776ab' },
  { id: 'tensorflow', name: 'TensorFlow', category: 'ai', size: 20, color: '#ff6f00' },
  { id: 'pytorch', name: 'PyTorch', category: 'ai', size: 20, color: '#ee4c2c' },
];

// 技术栈连接数据
const techLinks = [
  { source: 'frontend', target: 'react', strength: 1 },
  { source: 'frontend', target: 'typescript', strength: 1 },
  { source: 'frontend', target: 'vite', strength: 0.8 },
  { source: 'frontend', target: 'router', strength: 0.8 },
  { source: 'frontend', target: 'less', strength: 0.7 },
  { source: 'frontend', target: 'antd', strength: 0.9 },
  { source: 'frontend', target: 'axios', strength: 0.7 },
  { source: 'frontend', target: 'echarts', strength: 0.6 },
  { source: 'frontend', target: 'canvas', strength: 0.6 },
  { source: 'backend', target: 'node', strength: 1 },
  { source: 'backend', target: 'python', strength: 0.9 },
  { source: 'ai', target: 'python', strength: 1 },
  { source: 'ai', target: 'tensorflow', strength: 0.9 },
  { source: 'ai', target: 'pytorch', strength: 0.9 },
  { source: 'react', target: 'typescript', strength: 0.8 },
  { source: 'react', target: 'router', strength: 0.7 },
  { source: 'react', target: 'antd', strength: 0.7 },
  { source: 'antd', target: 'less', strength: 0.6 },
  { source: 'echarts', target: 'canvas', strength: 0.7 },
];

interface PerformanceMetrics {
  pageLoadTime?: number // 页面加载时间（毫秒）
  firstPaint?: number // 首次绘制时间（毫秒）
  firstContentfulPaint?: number // 首次内容绘制时间（毫秒）
  domInteractive?: number // DOM 可交互时间（毫秒）
  domComplete?: number // DOM 完成时间（毫秒）
  resourceLoadTime?: Record<string, number> // 资源加载时间（键为资源名称，值为时间）
  memoryUsage?: number // 内存使用量（字节）
  customMarks?: Record<string, number> // 自定义性能标记
}

interface TrackEvent {
  eventName: string
  eventType: string
  timestamp: number
  pageUrl: string
  userId?: string
  data?: Record<string, unknown> // 建议也将这里的 any 改为 unknown
}

interface Env {
  timestamp: number;       // 时间戳（毫秒）
  userId: string;          // 用户ID
  pageUrl: string;         // 页面URL
  userAgent: string;       // 浏览器用户代理字符串
  browser: string;         // 浏览器类型（如 "Chrome/114"）
}

// 类型定义（与 PerformanceMonitor 对齐）
interface PerformanceData {
  metrics: ReturnType<typeof performanceMonitor.getMetrics>;
  events: ReturnType<typeof performanceMonitor.getEvents>;
}

const DemoPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<string>('1')
  const [canvasSize, setCanvasSize] = useState({ width: 800, height: 500 })
  const dashboardRef = useRef<HTMLDivElement>(null)

  const [perfData, setPerfData] = useState<
    | {
        metrics: PerformanceMetrics
        events: TrackEvent[]
        env: Env
      }
    | undefined
  >(undefined)
  
  const [realPerformanceData, setRealPerformanceData] = useState<
    | {
        metrics: PerformanceMetrics
        events: TrackEvent[]
        env: Env // 环境信息
      }
    | undefined
    >()
  
  const [isDataReady, setIsDataReady] = useState<boolean>(false) // 标记数据是否就绪



  
  // 模拟性能标记
  useEffect(() => {
    // 初始化性能监控
    // performanceMonitor.init({ endpoint: '/api/performance' });

    // 页面加载性能标记
    performanceMonitor.init({
      endpoint: '/api/performance/report', // 无后端时，endpoint 填任意字符串（不影响本地打印）
      userId: 'demo_anonymous_user', // 无用户系统时，填固定值或留空（工具类会默认设为 anonymous）
    })
    performanceMonitor.mark('demo_page_loaded')

    // 调整Canvas大小
    const handleResize = () => {
      const container = document.querySelector('.tech-canvas-wrapper')
      if (container) {
        const width = container.clientWidth
        const height = Math.min(500, window.innerHeight * 0.6)
        setCanvasSize({ width, height })
      }
    }

    handleResize()
    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  // 模拟用户交互事件
  const handleTabChange = (key: string) => {
    setActiveTab(key)
    performanceMonitor.mark(`tab_changed_to_${key}`)
    performanceMonitor.track('tab_change', 'user_interaction', { tabKey: key })
  }

  // 模拟按钮点击事件
  const handleButtonClick = () => {
    // 1. 标记按钮点击开始
    performanceMonitor.mark('button_clicked_start')

    // 2. 跟踪按钮点击事件
    performanceMonitor.track('performance_data_print', 'user_interaction', {
      buttonId: 'send-performance-btn',
      actionDesc: '触发真实数据渲染到白板和Canvas',
    })

    setTimeout(() => {
      // 3. 标记按钮点击结束，测量耗时
      performanceMonitor.mark('button_clicked_end')
      const clickToPrintDelay = performanceMonitor.measure(
        'button_click_to_print_duration',
        'button_clicked_start',
        'button_clicked_end'
      )

      // 4. 关键：从 performanceMonitor 获取完整数据（metrics + events + env）
      const metrics = performanceMonitor.getMetrics() // 性能指标
      const events = performanceMonitor.getEvents() // 埋点事件
      const env = {
        // 环境信息（与 performance.ts 中 sendData 的 env 一致）
        timestamp: Date.now(),
        userId: performanceMonitor.getUserId(), // 需在 performance.ts 加 getUserId 方法
        pageUrl: window.location.href,
        userAgent: navigator.userAgent,
        browser:
          navigator.userAgent.match(/(Chrome|Firefox|Safari)\/(\d+)/)?.[0] ||
          'Unknown',
      }

      // 5. 更新状态：传递数据给子组件，标记数据就绪
      setRealPerformanceData({ metrics, events, env })
      setIsDataReady(true) // 这一步必须有！否则子组件一直认为数据未准备好

      // 6. 调用 sendData（控制台打印数据）
      performanceMonitor.sendData()

      // 7. 提示用户
      message.success(
        `
      真实性能数据已渲染到白板！
      1. 查看下方白板获取详细数据
      2. 点击耗时：${
        clickToPrintDelay ? Math.round(clickToPrintDelay) + 'ms' : '约500ms'
      }
    `,
        5
      )
    }, 500)
  }

  const tabsItems = [
    // 1. 性能监控标签页（原 TabPane tab='性能监控'）
    {
      key: '1',
      label: '性能监控', // 标签标题
      children: (
        <>
          <Card className='demo-card'>
            <Title level={4}>性能监控工具</Title>
            <Paragraph>
              我们使用自定义的性能监控工具收集和分析页面性能数据，包括页面加载时间、资源加载情况、用户交互事件等，帮助我们持续优化用户体验。
            </Paragraph>
            <Button type='primary' onClick={handleButtonClick}>
              发送性能数据
            </Button>
          </Card>

          {/* 2. 新增：PerformanceVizCanvas 组件（数据就绪后渲染） */}
          {isDataReady && realPerformanceData && (
            <div
              style={{ margin: '20px 0', overflow: 'auto', maxHeight: '95vh' }}
            >
              <Card className='demo-card'>
                <Title level={5}>性能数据可视化（Canvas）</Title>
                {/* 新增图表高度调整为 800px，适配新增的 4 类指标 */}
                <PerformanceVizCanvas
                  metrics={realPerformanceData.metrics}
                  events={realPerformanceData.events}
                />
              </Card>
            </div>
          )}

          {/* 传递 props 给 DataDashboard */}
          <div ref={dashboardRef} className='dashboard-container'>
            <DataDashboard
              realPerformanceData={realPerformanceData}
              isDataReady={isDataReady}
            />
          </div>
        </>
      ),
    },
    // 2. 技术栈可视化标签页（原 TabPane tab='技术栈可视化'）
    {
      key: '2',
      label: '技术栈可视化', // 标签标题
      children: (
        <>
          <Card className='demo-card'>
            <Title level={4}>Canvas矢量绘图</Title>
            <Paragraph>
              下面的交互式图表使用Canvas技术绘制，展示了实验室的三大研究方向及其相关技术栈，通过力导向算法实现节点的自动布局和动态交互效果。
            </Paragraph>
          </Card>

          <Card className='tech-canvas-wrapper'>
            <TechCanvas
              width={canvasSize.width}
              height={canvasSize.height}
              nodes={techNodes}
              links={techLinks}
            />
          </Card>

          <Row gutter={[16, 16]} className='tech-legend'>
            {/* 原有技术栈说明卡片（不变）... */}
            <Col xs={24} md={8}>
              <Card
                className='legend-card'
                style={{ borderLeft: '4px solid #ff4757' }}
              >
                <Title level={5}>前端开发</Title>
                <Paragraph>React, TypeScript, Ant Design, Less, Vite</Paragraph>
              </Card>
            </Col>
            <Col xs={24} md={8}>
              <Card
                className='legend-card'
                style={{ borderLeft: '4px solid #2ed573' }}
              >
                <Title level={5}>后端开发</Title>
                <Paragraph>
                  Node.js, Python, Express, Django, RESTful API
                </Paragraph>
              </Card>
            </Col>
            <Col xs={24} md={8}>
              <Card
                className='legend-card'
                style={{ borderLeft: '4px solid #5352ed' }}
              >
                <Title level={5}>人工智能</Title>
                <Paragraph>
                  Python, TensorFlow, PyTorch, 机器学习, 深度学习
                </Paragraph>
              </Card>
            </Col>
          </Row>
        </>
      ),
    },
  ]


  return (
    <div className='demo-page'>
      <div className='demo-header'>
        <Title level={2}>性能检测</Title>
        <Paragraph className='demo-intro'>
          本页面展示了实验室网站使用的性能优化工具和Canvas矢量绘图技术，包括性能监控、数据可视化和交互式技术栈展示。
        </Paragraph>
      </div>

      {/* 用 items 替代 TabPane，删除原有的 TabPane 结构 */}
      <Tabs
        activeKey={activeTab}
        onChange={handleTabChange}
        className='demo-tabs'
        items={tabsItems} // 关键：使用 items 配置
      />
    </div>
  )
};

export default DemoPage;